<?php

/**
 * @author Tongle Xu <xutongle@gmail.com>
 * @copyright Copyright (c) 2003-2103 Jinan TintSoft development co., LTD
 * @license http://www.tintsoft.com/html/about/copyright/
 * @version $Id$
 */
namespace Leaps\Console;

/**
 * 控制台应用程序环境信息。
 *
 * It is a wrapper for the PHP `$_SERVER` variable which holds information about
 * the
 * currently running PHP script and the command line arguments given to it.
 *
 * @property array $params The command line arguments. It does not include the
 *           entry script name.
 *
 * @author Tongle Xu <xutongle@gmail.com>
 * @since 4.0
 */
class Request extends \Leaps\Base\Request {
	private $_params;

	/**
	 * 返回命令行参数。
	 *
	 * @return array the command line arguments. It does not include the entry
	 *         script name.
	 */
	public function getParams() {
		if (! isset ( $this->_params )) {
			if (isset ( $_SERVER ['argv'] )) {
				$this->_params = $_SERVER ['argv'];
				array_shift ( $this->_params );
			} else {
				$this->_params = [ ];
			}
		}
		return $this->_params;
	}

	/**
	 * 设置命令行参数。
	 *
	 * @param array $params the command line arguments
	 */
	public function setParams($params) {
		$this->_params = $params;
	}

	/**
	 * 处理当前请求到路由和相关的参数。
	 *
	 * @return array the first element is the route, and the second is the
	 *         associated parameters.
	 */
	public function resolve() {
		$rawParams = $this->getParams ();
		if (isset ( $rawParams [0] )) {
			$route = $rawParams [0];
			array_shift ( $rawParams );
		} else {
			$route = '';
		}

		$params = [ ];
		foreach ( $rawParams as $param ) {
			if (preg_match ( '/^--(\w+)(=(.*))?$/', $param, $matches )) {
				$name = $matches [1];
				$params [$name] = isset ( $matches [3] ) ? $matches [3] : true;
			} else {
				$params [] = $param;
			}
		}

		return [ $route,$params ];
	}
}
